﻿using MES.Desktop.Upgrade.DataAccess;
using MES.Desktop.Upgrade.Models;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MES.Desktop.Upgrade.ViewModels
{
    class MainViewModel : BindableBase
    {
        public int TotalCount { get; set; }

        private int _completed;
        /// <summary>
        /// 已下载完成的文件数
        /// </summary>
        public int Completed
        {
            get { return _completed; }
            set { SetProperty<int>(ref _completed, value); }
        }

        public ObservableCollection<FileModel> FileList { get; set; } =
            new ObservableCollection<FileModel>();


        public DelegateCommand StartCommand { get; set; }

        public MainViewModel(string[] files)
        {
            for (int i = 1; i <= files.Length; i++)
            {
                var file = files[i - 1];

                // Zhaoxi.PMS.Client.BLL.dll|UpgradeFiles|100
                string[] info = file.Split("|");
                int.TryParse(info[2], out int len);
                FileList.Add(new FileModel
                {
                    Index = i,
                    FileName = info[0],
                    FilePath = info[1],
                    FileLenght = len,
                    FileMd5 = info[3]
                });
            }

            StartCommand = new DelegateCommand(DoStart);
        }

        int index = 0;
        AutoResetEvent autoResetEvent = new AutoResetEvent(false);
        LocalAccess localAccess = new LocalAccess();
        private void DoStart()
        {
            Completed = 0;
            foreach (var file in FileList)
            {
                if (file.HasCompleted)
                {
                    Completed++;
                    continue;
                }
                file.ErrorMsg = "";
                file.HasError = false;
                file.State = "";
            }

            string server_host = System.IO.File.ReadAllText(".\\server");

            Task.Run(() =>
            {
                foreach (var file in FileList)
                {
                    if (file.HasCompleted) continue;

                    // 两个路径
                    // 1、本地路径
                    string local_file = System.IO.Path.Combine(file.FilePath, file.FileName);
                    if (!Directory.Exists(local_file))
                    {
                        Directory.CreateDirectory(file.FilePath);
                    }
                    // 2、Uri路径
                    string folder = file.FilePath;
                    folder = folder == ".\\" ? "none" : folder;
                    string web_file = folder + "/" + file.FileName;

                    WebAccess webAccess = new WebAccess(server_host);

                    Debug.WriteLine("VM开始下载：" + web_file);
                    webAccess.DownloadFile(web_file, local_file,
                        /// 当下载完成时回调
                        completed_ev =>
                        {
                            Debug.WriteLine("VM下载完成：" + web_file);
                            if (completed_ev != null && completed_ev.Error != null)
                            {
                                // 需要提示异常
                                file.ErrorMsg = completed_ev.Error.Message;
                                file.State = "异常";
                                file.StateColor = "Red";
                                file.HasError = true;
                            }
                            else
                            {
                                file.State = "完成";
                                file.StateColor = "Green";
                                file.HasCompleted = true;

                                // 更新本地记录
                                if (!localAccess.UpdateFileInfo(file.FileName, file.FileMd5))
                                {
                                    file.ErrorMsg = "更新本地记录异常";
                                    file.State = "异常";
                                    file.StateColor = "Red";
                                    file.HasError = true;
                                }
                            }
                            Completed++;
                            file.Progress = 0;
                            autoResetEvent.Set();
                        },

                        /// 当下载进程发生变化时回调
                        (progress, byte_len) =>
                        {
                            // 接收进度百分比和接收到的字节数
                            file.Progress = progress / 100;
                            file.CompletedLen = byte_len;
                        }
                      );

                    autoResetEvent.WaitOne();
                }

                if (FileList.ToList().Exists(f => !f.HasCompleted)) return;



                /// 2、关闭更新程序，打开主程序
                Application.Current.Dispatcher.Invoke(() =>
                {
                    // 系统主程序
                    Process.Start("MES.Desktop.exe");
                    System.Environment.Exit(0);
                });
            });

        }
    }
}
